package com.yuexunxinxi.carefree.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuexunxinxi.carefree.utils.AUsertThreadLocal;
import com.yuexunxinxi.carefree.utils.R;
import com.yuexunxinxi.carefree.entity.AUser;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 作者: 李咨辰
 * 文件名: MyFilter.java
 * 路径: com.xltz.web.filter
 * 时间: 2024-09-20 10:18
 * 版本: 1.0
 * 描述: TODO 拦截器
 **/

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断访问的方法是否为controller方法,如果是则直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 如果方法上标注了 @SkipLogin，或者类上标注了 @SkipLogin，跳过登录验证
        if (handlerMethod.hasMethodAnnotation(SkipLogin.class) || handlerMethod.getBeanType().isAnnotationPresent(SkipLogin.class)) {
            return true;
        }
        HttpSession session = request.getSession();
        AUser aUser = (AUser) session.getAttribute("user");
        if (aUser == null) {
            R responseBody = R.error(401, "没有登录，请登录后访问");
            // 将R对象转换为JSON格式
            String jsonResponse = new ObjectMapper().writeValueAsString(responseBody);
            // 设置响应类型为JSON，并写入响应
            // response.setStatus(HttpServletResponse.SC_FORBIDDEN); //返回403
            // response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置状态码为500
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(jsonResponse);
            return false;
        }
        AUsertThreadLocal.put(aUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AUsertThreadLocal.remove();
    }
}
